<?php
namespace app\admin\model;

use app\admin\model\validate\AlbumImg;
use app\common\helper\Obj2Array;

class AlbumImgModel extends \app\common\model\project_model\AlbumImgModel {
    public $err_msg;

    /**
     * 新增或者更新相册照片
     *
     * @param $album_id
     * @param $data
     * @param null $type
     * @return bool
     * @throws \Exception
     */
    public function createAll($album_id, $data, $type = null) {
        if (!$data = $this->formatAndCheck($album_id, $data)) {
            return false;
        }
        if ($type) { // 更新,先删除=照片
            $this->where(['album_id' => $album_id])->delete();
        }
        // 新增
        if (!$this->saveAll($data, false)) {
            $this->err_msg = $this->getError();
            return false;
        }
        return true;
    }

    /**
     * 格式化数据并检测
     *
     * @param $album_id
     * @param $data
     * @return array|bool
     */
    private function formatAndCheck($album_id, $data) {
        $list = [];
        $validate = new AlbumImg();
        foreach ($data['img_url'] as $key => $item) {
            $list[$key]['img_url'] = $item;
            $list[$key]['album_id'] = $album_id;
            $list[$key]['created_time'] = date('Y-m-d H:i:s', time());
            $list[$key]['updated_time'] = date('Y-m-d H:i:s', time());
        }
        foreach ($data['desc'] as $key => $item) {
            $list[$key]['desc'] = $item;
        }
        foreach ($data['sort'] as $key => $item) {
            $list[$key]['sort'] = $item;
        }
        // 检测
        foreach ($list as $item) {
            if (!$validate->check($item)) {
                $this->err_msg = $validate->getError();
                return false;
            }
        }
        return $list;
    }

    /**
     * 相册下的所有的照片
     *
     * @param $album_id
     * @return array|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getImg($album_id) {
        $img = $this->where(['album_id' => $album_id])->field(['created_time', 'updated_time'], true)->select();
        if (!empty($img)) {
            $img = Obj2Array::resObject2Array($img);
        }
        return $img;
    }
}